package com.owen.he.jee.service.subService;

import java.beans.IntrospectionException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.owen.he.jee.service.exception.ServiceException;
import com.owen.he.jee.utils.excel.ExcelFileUtils;
import com.owen.he.jee.vo.excel.ImportExcelResult;

/**
 * 导入excel通用接口封装
 * @author owen.he
 */
@Service
public class ExcelImportService {

	private static final Logger logger = LoggerFactory.getLogger(ExcelImportService.class);
	
	
	/**
	 * excel导入处理
	 * 1.解析文件流得到到List<Object>
	 * 2.传出excel结果集对象进行，返回处理结果
	 * @param file excel的文件流
	 * @param invoker 调用者的回调器
	 * @param clazz 封装的excel的对象
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public ImportExcelResult doImport(InputStream file, ImportResultInvoker invoker, Class<?> clazz) {
		ImportExcelResult result = new ImportExcelResult();
		logger.info("开始解析excel的文件流");
		//1.将文件流解析问List<Object>
		List tmpList = new ArrayList<>();
		try {
			tmpList = ExcelFileUtils.readStreamFiles(file, 0, clazz);
		} catch (InstantiationException | IllegalAccessException | NoSuchFieldException | IllegalArgumentException
				| InvocationTargetException | IOException e) {
			throw new ServiceException("解析文件出错："+e.getMessage());
		} catch (IntrospectionException e) {
			throw new ServiceException("格式错误，请检查上传的模版："+e.getMessage());
		}
		//2.将解析的excel对象，交给调用者，校验保存
		logger.info("获取的List结果集对象，共有{}记录",tmpList.size());
		if(tmpList != null && tmpList.size() > 0) {
			for (int i = 0; i < tmpList.size(); i++) {
				Object obj = tmpList.get(i);
				//将解析的对象逐一给调用者进行处理，并返回结果
				ImportExcelResult rest = invoker.invokerResult(obj);
				if(rest != null) {
					logger.info("处理第{}条记录，返回的结果：{}",i+1,rest.toString());
					List err = rest.getErrotResult();//获取错误的记录，没有为null
					if(err != null) {
						result.getErrotResult().addAll(err);
					}
					boolean isOk = rest.isRecordIsOk();//此条记录是否处理成功
					if(isOk) {
						//处理成功+1
						int successRecord = result.getSuccessRecord();
						result.setSuccessRecord(successRecord+1);
					}else {
						//处理失败+1
						int failResord = result.getFailRecord();
						result.setFailRecord(failResord+1);
					}
					Map<String, Object> mesageResult = rest.getMesageResult();
					if(mesageResult!=null) {
						if(mesageResult.containsKey("error")) {
							result.getMesageResult().put(i+1+"", mesageResult.get("error"));
						}else {
							result.getMesageResult().put(i+1+"", "数据有异常");
						}
					}
				}else {
					logger.info("处理第{}条记录，无返回结果",i+1);
				}
			}
		}else {
			throw new ServiceException("excel的结果集为空，导入结束。");
		}
		logger.info("导入完成，返回的信息有：{}",result.toString());
		return result;
	}
	
	/**
	 * 调用者实现excel结果集校验，入库
	 * @author owen.he
	 *
	 */
	public interface ImportResultInvoker {
		/**
		 * 调用者调用，返回处理结果对象
		 * @param obj 解析excel得到的对象
		 * @return
		 */
		ImportExcelResult invokerResult(Object obj);
	}
}

